import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Logger,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { LogService } from '../log.service';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger(LoggingInterceptor.name);

  constructor(private readonly logService: LogService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest();
    const response = context.switchToHttp().getResponse();
    const { method, url, ip, headers } = request;
    const userAgent = headers['user-agent'] || '';
    const startTime = Date.now();

    // 获取用户信息（如果有认证）
    const user = request.user;
    const userId = user?.id || 0;
    const username = user?.username || 'Anonymous';

    // 仅记录管理员相关操作
    if (this.shouldLog(url)) {
      return next.handle().pipe(
        tap(async (data) => {
          const endTime = Date.now();
          const duration = endTime - startTime;
          const statusCode = response.statusCode;

          // 自动记录HTTP请求日志（仅管理员操作）
          await this.logService.logAdminOperation(
            userId,
            username,
            `HTTP_${method}`,
            'API',
            undefined,
            url,
            {
              method,
              url,
              statusCode,
              duration,
              userAgent,
              headers: this.sanitizeHeaders(headers),
            },
            ip,
            userAgent,
            statusCode >= 200 && statusCode < 300 ? 1 : 2, // 成功或失败
          );

          // 记录到控制台
          this.logger.log(
            `${method} ${url} - ${statusCode} - ${duration}ms - User: ${username} (${userId})`
          );
        }),
        catchError((error) => {
          // 记录错误日志
          this.logger.error(
            `${method} ${url} - Error: ${error.message}`,
            error.stack
          );
          throw error;
        }),
      );
    }

    // 对于不需要记录的请求，直接返回
    return next.handle();
  }

  /**
   * 判断是否需要记录该请求
   */
  private shouldLog(url: string): boolean {
    // 记录管理员相关的API
    return url.includes('/api/admin/') || 
           url.includes('/admin/') ||
           // 记录登录相关操作
           url.includes('/login') ||
           url.includes('/logout') ||
           // 记录CRUD操作
           (url.includes('/api/') && 
            (url.includes('/create') || 
             url.includes('/update') || 
             url.includes('/delete') ||
             url.includes('/publish') ||
             url.includes('/review')));
  }

  /**
   * 清理敏感头部信息
   */
  private sanitizeHeaders(headers: any): any {
    const sanitized = { ...headers };
    const sensitiveKeys = ['authorization', 'cookie', 'x-api-key', 'token'];
    
    sensitiveKeys.forEach(key => {
      if (sanitized[key]) {
        sanitized[key] = '[REDACTED]';
      }
    });
    
    return sanitized;
  }
}